package com.pactera.miyuangroup.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.pactera.miyuangroup.common.Constants;
import com.pactera.miyuangroup.common.RedisOperation;
import com.pactera.miyuangroup.config.CommonConfig;
import com.pactera.miyuangroup.db.entity.LoginUser;
import com.pactera.miyuangroup.db.entity.VehicleInfo;
import com.pactera.miyuangroup.db.entity.VendorInfo;
import com.pactera.miyuangroup.db.entity.VendorPassageway;
import com.pactera.miyuangroup.db.enums.ShowState;
import com.pactera.miyuangroup.db.mapper.VendorInfoMapper;
import com.pactera.miyuangroup.db.mapper.VendorPassagewayMapper;
import com.pactera.miyuangroup.service.MiyuanDataService;
import com.pactera.miyuangroup.service.VehicleInfoService;
import com.pactera.miyuangroup.service.VendorInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pactera.miyuangroup.service.VendorPassagewayService;
import com.pactera.miyuangroup.vo.request.app.AppPageVenderGoodsReq;
import com.pactera.miyuangroup.vo.request.app.AppPageVenderReq;
import com.pactera.miyuangroup.vo.request.web.VendorInfoRequest;

import com.pactera.miyuangroup.vo.response.app.AppPageVenderGoodsRes;
import com.pactera.miyuangroup.vo.response.app.AppPageVenderRes;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanModel;
import com.pactera.miyuangroup.vo.response.miyuan.MiYuanPage;
import com.pactera.miyuangroup.vo.response.miyuan.UserInfo;
import com.pactera.miyuangroup.vo.response.miyuan.VendorPassagewaySaleInfo;
import com.pactera.miyuangroup.vo.response.web.VehicleInfoRes;
import com.pactera.miyuangroup.vo.response.web.VendorInfoRes;
import com.pactera.miyuangroup.vo.response.web.VendorPassagewayRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * <p>
 * 售货机 服务实现类
 * </p>
 *
 * @author WangWu
 * @since 2018-04-13
 */
@Service
@Slf4j
public class VendorInfoServiceImp extends ServiceImpl<VendorInfoMapper, VendorInfo> implements VendorInfoService {

    @Autowired
    private CommonConfig config;
    @Autowired
    private VehicleInfoService vehicleInfoService;
    @Autowired
    private VendorPassagewayService vendorPassagewayService;
    @Autowired
    private VendorPassagewayMapper vendorPassagewayMapper;

    @Autowired
    private RedisOperation redis;

    @Autowired
    private MiyuanDataService miyuanDataService;


    @Override
    public Page<VendorInfoRes> getVendorInfoList(VendorInfoRequest vendorInfoRequest, String ordId) {
        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        //过滤没有工控号的售货机
        wrapper.where("`vendor`.`control_number` is not NULL");

        //如果提交了管理司员编号 先查询车辆ID
        if (StringUtils.isNotBlank(vendorInfoRequest.getJobNumber())) {

            EntityWrapper wper = new EntityWrapper();
            wper.eq("`user`.`job_number`", vendorInfoRequest.getJobNumber());
            wper.eq("`vehicle`.`organization_id`", ordId);

            VehicleInfoRes vehicleInfoPO = baseMapper.selectOneVehicleInfo(wper);

            log.info("提交了JobNumber：", vendorInfoRequest.getJobNumber());
            //判断 vehicleInfoDO 对象是否为空
            if (vehicleInfoPO == null) {


                return null;
            }
            wrapper.eq("vehicle_id", vehicleInfoPO.getId());

        }

        if (!Constants.SYS_ROOT.equals(ordId)) {
            wrapper.eq("organization_id", ordId);
        }
        if (StringUtils.isNotBlank(vendorInfoRequest.getNumber())) {
            wrapper.eq("number", vendorInfoRequest.getNumber());
        }

        if (StringUtils.isNotBlank(vendorInfoRequest.getControlNumber())) {
            wrapper.eq("control_number", vendorInfoRequest.getControlNumber());
        }

        if (StringUtils.isNotBlank(vendorInfoRequest.getModelNumber())) {
            wrapper.eq("model_number", vendorInfoRequest.getModelNumber());
        }


        //查询数据
        Page<VendorInfoRes> VendorInfoRes = new Page<VendorInfoRes>(vendorInfoRequest.getCurrent(), vendorInfoRequest.getSize());

        List<VendorInfoRes> VendorInfoResListPO = baseMapper.selectVehicleInfoResList(VendorInfoRes, wrapper);

        VendorInfoRes.setRecords(VendorInfoResListPO);

        return VendorInfoRes;
    }

    @Override
    public List<VendorPassagewayRes> getPassagewayList(String vendorId) {
        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        if (StringUtils.isNotBlank(vendorId)) {
            //查询数据
            log.info("售货机ID：{}", vendorId);
            wrapper.eq("`way`.`vendor_id`", vendorId);
            wrapper.orderBy("`way`.passageway_number");
            List<VendorPassagewayRes> PassagewayResList = baseMapper.selectOnePassagewayList(wrapper);
            return PassagewayResList;
        } else {
            log.info("没有提交售货机ID，返回空数据");
            return null;
        }


    }

    /**
     * APP 查询用户售货机
     *
     * @param userId  用户ID
     * @param request
     * @return
     */
    @Override
    public Page<AppPageVenderRes> getAppVendorInfoList(String userId, AppPageVenderReq request) {

        //查询数据
        log.info("用户ID：{}", userId);
        if (StringUtils.isBlank(userId)) {
            return new Page<>();
        }

        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.where("user_id={0}", userId);
        if (StringUtils.isNotBlank(request.getParameter())) {
            wrapper.andNew().like("point_name", request.getParameter())
                    .or("point_number={0}", request.getParameter()).or("number={0}", request.getParameter());
        }
        //查询分页
        Page<AppPageVenderRes> page = new Page<>(request.getCurrent(), request.getSize());
        List<AppPageVenderRes> pageList = baseMapper.selectAppPageVenderInfo(page, wrapper);
        page.setRecords(pageList);

        //查询售货机实际销售情况
        for (AppPageVenderRes vender : page.getRecords()) {
            Integer total = baseMapper.selectVendorPassagewayTotal(vender.getId());
            if (null == total) {
                log.error("售货机货道总数异常：{}", vender.getId());
                total = 0;
            }
            vender.setTotal(total);
            //售货机所有售卖总数
            MiYuanModel<MiYuanPage<VendorPassagewaySaleInfo>> miYuanModel = miyuanDataService.getVendorPassagewaySaleInfo(vender.getNumber());
            boolean flg = miYuanModel.isSuccess() && null != miYuanModel.getData() && null != miYuanModel.getData().getRecords() && miYuanModel.getData().getRecords().size() > 0;
            int sell = 0;
            if (flg) {
                sell = miYuanModel.getData().getRecords().stream().map(s -> {
                    return Integer.parseInt(s.getNumber());
                }).reduce(0, Integer::sum);
            }
            BigDecimal ratio = BigDecimal.ZERO;
            if (null != vender.getTotal() && sell > 0 && vender.getTotal().intValue() > 0) {
                ratio = new BigDecimal(sell).divide(new BigDecimal(vender.getTotal()), 4, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
            }
            log.info("售货机【{}】销售比率：{}", vender.getId(), ratio);
            vender.setSalesRatioString(ratio);
        }
        //排序
        page.getRecords().sort((h1, h2) -> h2.getSalesRatioString().compareTo(h1.getSalesRatioString()));
        return page;
    }


    /**
     * app 查询售货机商品信息
     *
     * @param vendorId
     * @param req
     * @return
     */
    @Override
    public Page<AppPageVenderGoodsRes> getAppVenderGoodsInfoList(String vendorId, AppPageVenderGoodsReq req) {
        //查询数据
        log.info("售货机ID：{}", vendorId);
        if (StringUtils.isBlank(vendorId)) {
            return new Page<>();
        }
        //查询售货机信息
        VendorInfo vendorInfo = selectById(vendorId);
        //验证数据
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("vendor_id", vendorId);
        if (StringUtils.isNotBlank(req.getClassificationId())) {
            wrapper.eq("classification", req.getClassificationId());
        }
        wrapper.orderBy("passageway_number", true);
        Page<AppPageVenderGoodsRes> page = new Page<>(req.getCurrent(), req.getSize());
        List<AppPageVenderGoodsRes> pageList = vendorPassagewayMapper.getAppVenderGoods(page, wrapper);
        page.setRecords(pageList);

        //售货机所有售卖总数
        MiYuanModel<MiYuanPage<VendorPassagewaySaleInfo>> miYuanModelPage = MiYuanModel.fail();
        if (null != vendorInfo && StringUtils.isNotBlank(vendorInfo.getNumber())) {
            miYuanModelPage = miyuanDataService.getVendorPassagewaySaleInfo(vendorInfo.getNumber());
        }
        //售货机所有售卖总数
        boolean flg = miYuanModelPage.isSuccess() && null != miYuanModelPage.getData() && null != miYuanModelPage.getData().getRecords() && miYuanModelPage.getData().getRecords().size() > 0;
        List<VendorPassagewaySaleInfo> vendorPassagewaySaleInfos = new ArrayList<>();
        if (flg) {
            vendorPassagewaySaleInfos = miYuanModelPage.getData().getRecords();
        }
        //查询售货机实际销售情况
        for (AppPageVenderGoodsRes vender : page.getRecords()) {
            VendorPassagewaySaleInfo vendorPassagewaySaleInfo = vendorPassagewaySaleInfos.stream().filter(v -> vender.getPassagewayNumber().equals(new Integer(v.getChannelNum()).toString())).findFirst().orElse(null);
            if (null != vendorPassagewaySaleInfo) {
                //库存
                int inventory = (vender.getMaxNumber().intValue() - Integer.parseInt(vendorPassagewaySaleInfo.getNumber()));
                vender.setInventory(inventory);
                //待补
                vender.setSold(Integer.parseInt(vendorPassagewaySaleInfo.getNumber()));
            } else {
                //库存
                vender.setInventory(0);
                //待补
                vender.setSold(0);
            }
        }
        return page;
    }

    /**
     * 同步售货机
     *
     * @return
     */
    @Override
    public boolean syncMiyuanVenderInfo() {
        //miYuanVenderInfo();
//        //开始更新
//        boolean flg = redis.get(Constants.REDIS_MIYUAN_VENDER_INFO_SYNC, Boolean.class, Boolean.TRUE);
//        if (!flg) {
//            return false;
//        }
        miYuanVenderInfo();
        return true;
    }

    /**
     * 同步米源数据
     */
    private void miYuanVenderInfo() {
        ExecutorService executor2 = Executors.newFixedThreadPool(config.getVendorThreadPool());
        try {
            redis.set(Constants.REDIS_MIYUAN_VENDER_INFO_SYNC, Boolean.FALSE);
            //查询所有车辆信息
            List<VehicleInfo> vehicleInfos = vehicleInfoService.selectList(null);
            for (VehicleInfo vehicleInfo : vehicleInfos) {
                //使用多线程
                executor2.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            VenderInfo(vehicleInfo);
                        } catch (Exception e) {
                            log.error("同步米源售货机信息发生异常", e);
                        }
                    }
                });
            }
            executor2.shutdown();
            redis.set(Constants.REDIS_MIYUAN_VENDER_INFO_SYNC, Boolean.TRUE);
        } catch (Exception e) {
            log.error("同步米源售货机信息发生异常", e);
            redis.set(Constants.REDIS_MIYUAN_VENDER_INFO_SYNC, Boolean.TRUE);
        }
    }

    private void VenderInfo(VehicleInfo vehicleInfo) {
        MiYuanModel<List<com.pactera.miyuangroup.vo.response.miyuan.VendorInfo>> miyuan = miyuanDataService.getVendorInfo(vehicleInfo.getLicensePlate());

        //查询是否成功
        if (!miyuan.isSuccess()) {
            return;
        }

        //查询是否成功
        if (null == miyuan.getData() || miyuan.getData().size() <= 0) {
            return;
        }

        //更新售货机集合
        List<VendorInfo> upInfos = new ArrayList<>();
        //新增售货机集合
        List<VendorInfo> instInfos = new ArrayList<>();

        //循环数据入库
        for (com.pactera.miyuangroup.vo.response.miyuan.VendorInfo vendorInfo : miyuan.getData()) {
            //查询数据库是否存在数据
            EntityWrapper<VendorInfo> ew = new EntityWrapper<>();
            if (StringUtils.isNotBlank(vendorInfo.getNumber())) {
                /**售货机编号不为空*/
                ew.eq("number", vendorInfo.getNumber());
            } else {
                ew.eq("original_id", vendorInfo.getId());
            }
            VendorInfo info = selectOne(ew);
            if (null != info) {
                //存在，更新数据
                info.setVehicleId(vehicleInfo.getId());
                info.setNumber(vendorInfo.getNumber());
                info.setControlNumber(vendorInfo.getControlNumber());
                info.setModelNumber(vendorInfo.getModelNumber());
                info.setSpecifications(vendorInfo.getSpecifications());
                if (StringUtils.isNotBlank(vendorInfo.getLaunchDate())) {
                    info.setLaunchDate(com.pactera.miyuangroup.util.Date.parseDate(vendorInfo.getLaunchDate(), new SimpleDateFormat("yyyy-MM-dd")));
                }
                info.setPointName(vendorInfo.getPointName());
                info.setPointNumber(vendorInfo.getPointNumber());
                info.setOriginalId(vendorInfo.getId());
                info.setOrganizationId(vehicleInfo.getOrganizationId());
                upInfos.add(info);
            } else {
                //不存在，新增数据
                info = new VendorInfo();
                info.setVehicleId(vehicleInfo.getId());
                info.setNumber(vendorInfo.getNumber());
                info.setControlNumber(vendorInfo.getControlNumber());
                info.setModelNumber(vendorInfo.getModelNumber());
                info.setSpecifications(vendorInfo.getSpecifications());
                if (StringUtils.isNotBlank(vendorInfo.getLaunchDate())) {
                    info.setLaunchDate(com.pactera.miyuangroup.util.Date.parseDate(vendorInfo.getLaunchDate(), new SimpleDateFormat("yyyy-MM-dd")));
                }
                info.setPointName(vendorInfo.getPointName());
                info.setPointNumber(vendorInfo.getPointNumber());
                info.setOriginalId(vendorInfo.getId());
                info.setOrganizationId(vehicleInfo.getOrganizationId());
                instInfos.add(info);
            }
        }

        //更新
        if (upInfos.size() > 0) {
            updateBatchById(upInfos, upInfos.size());
        }
        //新增
        if (instInfos.size() > 0) {
            insertBatch(instInfos, instInfos.size());
        }
    }

}
